<template>
  <div class="serviceposition-manage">
    <div class="main-title">新建/编辑</div>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      class="dataForm"
      label-position="right"
      label-width="100px"
    >
     <el-form-item label="类型" prop="type">
        <el-select
          v-model="form.type"
          style="width: 100%"
          placeholder="请选择类型"
        >
          <el-option
            v-for="item in dict.FWZD"
            :key="item.id"
            :label="item.dictName"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入名称"
          clearable
          :style="{ width: '100%' }"
          maxlength="40"
        />
      </el-form-item>
      <el-form-item label="驿站位置" required>
        <div class="map-con">
          <div class="demo-input-suffix">
            <el-link type="info">经度：</el-link>
            <el-input
              v-model.number="locData.longitude"
              class="lineinput"
              style="width: 200px"
              size="mini"
            />
            <el-link type="info">纬度：</el-link>
            <el-input
              v-model.number="locData.latitude"
              class="lineinput"
              style="width: 200px"
              size="mini"
            />
            <!-- <el-link type="info">地址：</el-link>
            <el-input
              v-model.trim="locData.address"
              class="lineinput"
              style="width:200px"
              size="mini"
            />-->
          </div>
          <baidu-map
            class="map"
            :center="center"
            :zoom="zoom"
            :scroll-wheel-zoom="true"
            ak="33B192o1jPaqOHASGGAIkoMuwi8W76j3"
            @ready="handler"
            @click="clickEvent"
          >
            <!--地图控件位置-->
            <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT" />
            <!--城市列表-->
            <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT" />
            <!--定位当前位置-->
            <bm-geolocation
              anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
              :show-address-bar="true"
              :auto-location="true"
              @locationSuccess="getLoctionSuccess"
            />
            <bm-view :style="{ width: '100%', height: '500px', flex: 1 }" />
          </baidu-map>
        </div>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="form.address"
          placeholder="请输入详细地址"
          clearable
          :style="{ width: '100%' }"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="telephone">
        <el-input
          v-model="form.telephone"
          placeholder="请输入电话"
          clearable
          :style="{ width: '100%' }"
        />
      </el-form-item>
<!-- 
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status" size="medium">
          <el-radio
            v-for="(item, index) in dict.ZT"
            :key="index"
            :label="item.dictValue"
            >{{ item.dictName }}</el-radio
          >
        </el-radio-group>
      </el-form-item> -->
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button style="padding: 10px 30px" @click="cancel()">取消</el-button>
      <!-- <el-button style="padding: 8px 30px;" type="primary" @click="view">预览</el-button> -->
      <el-button
        type="primary"
        @click="state === 'create' ? createData() : updateData()"
        >确定</el-button
      >
    </div>
    <preview
      :dialog-status="isShowPreview"
      :title="form.name"
      :content="form.introduction"
      @onclose="closePreview()"
    />
  </div>
</template>
<script>
import {
  insert,
  update,
  get,
  getDictByCode
} from '@/views/staffserve/axyz/api/manage'
import Preview from '@/components/Preview'
import { BaiduMap, BmNavigation, BmView, BmGeolocation, BmCityList } from 'vue-baidu-map'
import CryptoJS from '@/utils/aesJiaJM'
import { checkPhone } from '@/utils/validate'
export default {
  name: 'ServicepositionManage',
  components: {
    Preview,
    BaiduMap,
    BmNavigation,
    BmView,
    BmGeolocation,
    BmCityList
  },
  data() {
    return {
      form: {
        type: '',
        name: '',
        telephone: '',
        introduction: '',
        address: '',
        status: 'ZT01',
        longitude: '',
        latitude: '',
        city: ''
      },
      rules: {
        type: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '请输入电话', trigger: 'blur' }, { validator: checkPhone, trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '请输入介绍', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '', trigger: 'change' }
        ],
        longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
        latitude: [{ required: true, message: '请输入纬度', trigger: 'blur' }]
      },
      dict: {
				FWZD:[]
      },
      isShowPreview: false,
      t: '',
      center: { lng: '', lat: '' },
      zoom: 12,
      mapVisible: true,
      locData: {
        longitude: '',
        latitude: '',
        address: ''
      },
      iconUrl: require('../images/map-icon.png'),
      classifyList: []
    }
  },
  computed: {},
  watch: {},
  created() {
    for (const key in this.dict) {
			console.log(key)
      this.getDict(key)
    }
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    if (this.$route.query.type === 'u') {
      this.getFormInfo(this.$route.query.i)
    }
  },
  mounted() { },
  methods: {
    closePreview() {
      this.isShowPreview = false
    },

    view() {
      this.isShowPreview = true
    },
    getDict(code) {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
		
				}).catch(error => {
					console.log('error',error)
        })
 
    },


    getFormInfo(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get(id).then(res => {
          loading.close()
          const {
            id,
            type,
            name,
            telephone,
            address,
            city,
            latitude,
            longitude,
            introduction,
            status
          } = res.data.data
          this.$set(this, 'form', {
            id,
            type,
            name,
            telephone,
            address,
            city,
            latitude,
            longitude,
            introduction,
            status
          })
          this.$set(this, 'locData', { latitude, longitude })
          // this.$set(this.form, 'telephone', CryptoJS.$aesJieM(this.form.telephone))
          this.$nextTick(() => {
            this.$refs['form'].clearValidate()
          })
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },

    cancel() {
      this.$router.push({ path: this.$filterPath('index'), query: { t: this.t } })
    },

    createData() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.locData && this.locData.longitude && this.locData.latitude) {
            this.form.longitude = this.locData.longitude
            this.form.latitude = this.locData.latitude
          } else {
            this.$message({
              message: '请选择驿站位置',
              type: 'warning'
            })
            return
          }
          const params = {
            type: this.form.type,
            name: this.form.name,
            // telephone: CryptoJS.$aesJiaM(this.form.telephone),
            telephone: this.form.telephone,
            introduction: this.form.introduction,
            address: this.form.address,
            city: this.form.city,
            status: this.form.status,
            longitude: this.form.longitude,
            latitude: this.form.latitude
          }
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          insert(params).then(res => {
            loading.close()
            this.$message({
              title: '成功',
              message: '创建成功！',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.$router.push({ path: this.$filterPath('index'), query: { t: this.t } })
              }
            })
          }).catch(() => {
            loading.close()
          })
        }
      })
    },
    updateData() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.locData && this.locData.longitude && this.locData.latitude) {
            this.form.longitude = this.locData.longitude
            this.form.latitude = this.locData.latitude
          } else {
            this.$message({
              message: '请选择驿站位置',
              type: 'warning'
            })
            return
          }
          const params = {
            id: this.form.id,
            type: this.form.type,
            name: this.form.name,
            // telephone: CryptoJS.$aesJiaM(this.form.telephone),
            telephone: this.form.telephone,
            introduction: this.form.introduction,
            address: this.form.address,
            city: this.form.city,
            status: this.form.status,
            longitude: this.form.longitude,
            latitude: this.form.latitude
          }
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          update(params).then(res => {
            loading.close()
            this.$message({
              title: '成功',
              message: '编辑成功！',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.$router.push({ path: this.$filterPath('index'), query: { t: this.t } })
              }
            })
          }).catch(() => {
            loading.close()
          })
        }
      })
    },
    handler({ BMap, map }) {
      const _this = this
      var geolocation = new BMap.Geolocation()
      geolocation.getCurrentPosition((r) => {
        let lng = ''
        let lat = ''
        if (_this.form.longitude && this.form.latitude) {
          lng = _this.form.longitude
          lat = _this.form.latitude
        } else {
          lng = r.longitude
          lat = r.latitude
        }
        _this.center = { lng: lng, lat: lat }		// 设置center属性值
        _this.autoLocationPoint = { lng: lng, lat: lat }		// 自定义覆盖物
        _this.initLocation = true
        if (_this.state === 'update') {
          window.map.clearOverlays()
          const Icon_0 = new BMap.Icon(this.iconUrl, new BMap.Size(64, 64), { anchor: new BMap.Size(18, 32), imageSize: new BMap.Size(36, 36) })
          var myMarker = new BMap.Marker(new BMap.Point(lng, lat), { icon: Icon_0 })
          window.map.addOverlay(myMarker)
        }
      }, { enableHighAccuracy: true })

      window.map = map
    },
    // 点击地图监听
    clickEvent(e) {
      window.map.clearOverlays()
      const Icon_0 = new BMap.Icon(this.iconUrl, new BMap.Size(64, 64), { anchor: new BMap.Size(18, 32), imageSize: new BMap.Size(36, 36) })
      var myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat), { icon: Icon_0 })
      window.map.addOverlay(myMarker)
      // 用所定位的经纬度查找所在地省市街道等信息
      var point = new BMap.Point(e.point.lng, e.point.lat)
      var gc = new BMap.Geocoder()
      const _this = this
      gc.getLocation(point, (rs) => {
        _this.form.city = rs.addressComponents.city
        _this.locData.address = rs.address
      })
      this.locData.longitude = e.point.lng
      this.locData.latitude = e.point.lat
    },
    // 定位成功回调
    getLoctionSuccess(point, AddressComponent, marker) {
      window.map.clearOverlays()
      const Icon_0 = new BMap.Icon(this.iconUrl, new BMap.Size(64, 64), { anchor: new BMap.Size(18, 32), imageSize: new BMap.Size(36, 36) })
      var myMarker = new BMap.Marker(new BMap.Point(point.point.lng, point.point.lat), { icon: Icon_0 })
      window.map.addOverlay(myMarker)
      this.locData.longitude = point.point.lng
      this.locData.latitude = point.point.lat
    }
  }
}
</script>
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
@import "@/styles/mixin.scss";
.serviceposition-manage {
  width: 100%;
  background-color: #fff;
  padding: 10px;
  .main-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-serviceposition: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: "";
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }
  .dataForm {
    margin-top: 20px;
  }
}
</style>
